package com.fx.smsclient.modules.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.fx.smsclient.util.GsonTool;
import com.zx.sms.BaseMessage;
import com.zx.sms.codec.cmpp.msg.CmppDeliverRequestMessage;
import com.zx.sms.codec.cmpp.msg.CmppSubmitResponseMessage;
import com.zx.sms.connect.manager.EventLoopGroupFactory;
import com.zx.sms.connect.manager.ExitUnlimitCirclePolicy;
import io.netty.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.util.concurrent.Callable;
import java.util.concurrent.LinkedBlockingQueue;

@Service
@Order(value=100)
public class CallBackMsgService implements CommandLineRunner {
    @Value("${callback.url}")
    private String callbackUrl;
    private static LinkedBlockingQueue<BaseMessage> linkedMsgQueue = new LinkedBlockingQueue<>();
    private static final Logger logger = LoggerFactory.getLogger(CallBackMsgService.class);

    static public void put(BaseMessage msg){
        try {
            linkedMsgQueue.put(msg);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void startLoopTask() {
        EventLoopGroupFactory.INS.submitUnlimitCircleTask(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                while (linkedMsgQueue.size() != 0) {
                    BaseMessage msg = linkedMsgQueue.take();
                    if (msg instanceof CmppDeliverRequestMessage){
                        callback(msg);
                    }
                    if (msg instanceof CmppSubmitResponseMessage){
                        callback(msg);
                    }
                }
                return true;
            }
        }, new ExitUnlimitCirclePolicy<Boolean>() {
            @Override
            public boolean notOver(Future<Boolean> future) {
                return true;
            }

        }, 10);
    }

    private void callback(BaseMessage msg) {
        String json = GsonTool.toJson(msg);
        logger.info(json);
        if (ObjectUtil.isNotEmpty(callbackUrl)) {
            HttpUtil.post(callbackUrl, json);
        }
    }


    @Override
    public void run(String... args)  {
        startLoopTask();
    }
}
